<template>
  <div class="contentBox" style="height: 600px">
    <div class="content">
      <div class="leftTree">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          @node-click="handleNodeClick"
        />
      </div>
      <div class="cntTab">
        <template>
          <el-table
            v-loading="loading"
            :data="tableData"
            stripe
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column
              prop="name"
              label="流程名称"
            />
            <!--<el-table-column-->
              <!--prop="level"-->
              <!--label="问题级别"-->
              <!--width="100"-->
              <!--align="center"-->
            <!--&gt;-->
              <!--<template slot-scope="scope">-->
                <!--<span>{{ handLevel(scope.row.level) }}</span>-->
              <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column
              prop="date"
              label="操作"
              width="100"
              align="center"
            >
              <template slot-scope="{row}">
                <el-button
                  type="text"
                  @click="config(row)"
                >
                  发送
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <!-- 分页 -->
        <div class="pageBox">
          <el-pagination
            background
            :current-page.sync="currentPage"
            :page-size="10"
            layout="prev, pager, next, jumper"
            :total="total"
            @current-change="getForm"
          />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { Message } from 'element-ui'
import { v4 as uuidv4 } from 'uuid'
import { parseTime } from '@/utils';
import { MessageBox } from 'element-ui';
export default {
  filters: {
    statusFilter(time, cFormat) {
      return parseTime(time, cFormat)
    }
  },
  data() {
    return {
      addDialogVisible: false,
      editDialogVisible: false,
      delDialogVisible: false,
      loading: false,
      addLoading: false,
      editLoading: false,
      currentPage: 1,
      total: 0,
      current: 1,
      deptId: '',
      ruleForm: {},
      editRuleForm: {
        pDept: {}
      },
      searchObj: {
        deptId: ''
      },
      treeData: [],
      tableData: [],
      seleListData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      addModel:true,
      addFormVisible:false,
      page:1,
      addParams: {
        name: undefined,
        description: undefined,
        table_name: undefined,
        send_type: 'user'
      },
      currUser: JSON.parse(sessionStorage.getItem('user')),
      queryParams: {
        'name':''
      },
      catCode:'process',
      'userSelectOptions':[],
      currProcess:{},
      defName:'',
      defKey:'',
      showTemp:'showList'
    }
  },
  created() {
    // this.getTabTada({ current: 1, limit: 10 })
    this.getForm()
    this.getTree()
    this.getseleListData()
  },
  methods: {
    parseTime(){},
    // 执行操作
    handleCommand(obj){
      if(this[obj.opera]){
        this[obj.opera](obj.row);
      }
    },
    cb(){
      this.showTemp = 'showList'
    },
    handLevel(level){
      return level === '0' ? '初级' : level === '1' ? '中级' : '高级'
    },
    callData(data){
      this.showTemp = 'showList'
      let form = {}
      for(let key in data){
        form = data[key]
      }
      const params = {
        'c_process': {
          'bpmn_key':form.key,
          'status':'1',
          '@where':{
            'id@eq':this.currProcess.id
          }
        }
      }
      this.COM.jsonsqlForUpdate(params).then(() =>{

      })
    },
    config(row) {
      this.$emit('selectData',row)
    },
    processNameRules(rule, value, callback) {
      if (!value) return callback('请输入');
      callback()
    },
    nameRules(rule, value, callback) {
      var blank = new RegExp(/^[a-zA-Z]\w{5,39}$/);
      if (value) {
        if (!blank.test(value)) {
          return callback(new Error('表名只能包含大小写字母、数字和下划线，并且首字符必须为字母，长度6到40'))
        } else if (this.addModel){ // 新增流程才判断表名是否重复
          const params = {
            'information_schema.columns:data[]': {
              '@column': '*',
              '@where':{
                'table_name@eq': value.trim(),
                'table_schema@in':'SELECT database()'
              }
            }
          }
          this.COM.jsonsqlForSelect(params).then(res => {
            if(res.data && res.data.length  == 0) {
              this.COM.jsonsqlForSelect({
                'c_process:data[]':{
                  '@column':'id', //定义返回列
                  '@where':{ // 查询条件
                    'table_name@eq': value.trim(),
                  }
                }
              }).then(res => {
                if(res.data && res.data.length == 0) {
                  callback();
                } else {
                  callback(new Error('表名重复'));
                }
              })
            } else {
              callback(new Error('表名重复'));
            }
          })
        } else {
          callback();
        }
      } else {
        callback('请输入');
      }
    },
    getForm(){
      const params = {
        'c_process:data[]':{
          '@column':'*', //定义返回列
          '@where':{ // 查询条件
            'cat_code@like': `%${this.catCode}%`,
            'status@eq': '1',
            'name@like': `%${this.queryParams.name}%`
          },
          '@order':'create_time-',
          '@page':{ // 分页配置
            '@pageSize':10,
            '@pageNo':this.currentPage
          }
        }
      }
      this.COM.jsonsqlForSelect(params).then(res => {
        this.loading = false;
        this.tableData = res.data
        this.total = parseInt(res.total)
      }) .catch(() => {
        this.loading = false;
      })
    },
    closeProcee(){
      this.selectUserData = {}
      this.$refs.addForm.resetFields();
    },
    turnToAdd() {
      this.$refs.addForm.validate(value => {
        if (value) {
          this.addParams.cat_code = this.catCode;
          if (this.addModel){
            this.addParams.id = uuidv4()
            this.addParams.create_by = this.currUser.account
            this.addParams.create_time = new Date()
            this.COM.jsonsqlForInsert({
              'c_process':[this.addParams]
            }).then(() =>{
              this.$message.success('新增成功')
              this.addFormVisible = false
              this.getForm()
            }
            )
          } else {
            const params = JSON.parse(JSON.stringify(this.addParams))
            params['@where'] = {
              'id@eq':params.id
            }
            delete params.id
            params.update_by = this.currUser.account
            params.update_time = new Date()
            this.COM.jsonsqlForUpdate({
              'c_process':params
            }).then(() =>{
              this.$message.success('修改成功')
              this.addFormVisible = false
              this.getForm()
            }
            )
          }
        }
      })
    },
    deleteRow(row){
      const self = this
      MessageBox.confirm('此操作将永久删除, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          'c_process':{
            '@where': {
              'id@eq': row.id
            }
          }
        }
        self.COM.jsonsqlForDelete(params).then(() =>{
          self.$message.success('删除成功')
          self.getForm()
        })
      }).catch(() => {
        Message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getTree() {
      this.COM.jsonsqlForSelect({
        'sys_classification:data[]': {
          '@column': 'classification_id:id,pid:parentId,classification_name:label,cate_code:value',
          '@where':{
            'cate_code@like':'%process%'
          }
        }
      }).then(res => {
        this.treeData = this.COM.getTreeData(res.data, 1)
      }) .catch(() => {
        this.treeLoading = false;
      })
    },
    getseleListData() {
      this.$axios.get('/dept/pDept').then(res => {
        this.seleListData = res.data
      })
    },
    handleNodeClick(data) {
      // 树节点点击方法
      this.currentPage = 1;
      this.catCode = data.value;
      this.getForm();
    },
    add() {
      this.addModel = true
      this.userList = []
      this.addParams = {
        name: '',
        description: '',
        table_name: ''
      }
      this.addFormVisible = true;
    },
    edit(row) {
      this.addParams = {
        id: row.id,
        name: row.name,
        description: row.description,
        table_name: row.table_name
      }
      this.addModel = false
      this.addFormVisible = true;
    },
    handleCurrentChange(val) {
      // 分页跳转
      this.current = val
      this.getTabTada(this.searchObj, { current: val, limit: 10 })
    }
  }
}
</script>
<style lang="scss" scoped>
  .content {
    display: flex;
    height: calc(100% - 56px) !important;
    .leftTree {
      min-width: 200px;
      height: 100%;
      border: 1px solid #dfe6ec;
    }
    .cntTab {
      flex: 1;
      height: 100%;
      border: 1px solid #dfe6ec;
      border-left: none;
    }
    .el-dropdown-link {
      cursor: pointer;
      color: #1890ff;
    }
  }
</style>
